<template>
  <!-- 忘记密码 -->
  <div class="reset-pssword" v-bind="$attrs">
    <div class="reset-pssword__title">{{ t('login.reset') }}</div>
    <ZStepBar :steps="steps" v-model:active="stepActive"/>
    <el-form :model="resetPasswordForm" ref="resetPasswordFormRef" :rules="resetPasswordFormRules" class="demo-form-inline">
      <el-form-item prop="userName" v-if="!isPhoneLogin && stepActive === 1">
        <el-input autocomplete="off" v-model="resetPasswordForm.userName" :placeholder="t('login.accountPls')" />
      </el-form-item>
      <el-form-item prop="userName" class="phone-form" v-if="isPhoneLogin && stepActive === 1">
        <el-select v-model="resetPasswordForm.area" size="large">
          <el-option
            v-for="item in langAreaList"
            :key="item.countryCode"
            :label="item.countryCode"
            :value="item.countryCode"
          >
            <div class="phone-area-option">
              <img :src="item.resource" alt="">
              <span>{{ item.countryCode }}</span>
            </div>
          </el-option>
        </el-select>
        <el-input autocomplete="off" v-model="resetPasswordForm.userName" :placeholder="t('login.accountpho2')" />
      </el-form-item>
      <el-form-item prop="code" class="form-input-code" v-if="stepActive === 1">
        <el-input autocomplete="off" v-model="resetPasswordForm.code" :placeholder="t('login.verifiyInput')" />
        <el-button type="primary" size="large" @click="getCodeOfResetPassword" :disabled="!resetPasswordForm.userName || getResetPasswordCodeDisabled">{{ getResetPasswordCodeTxt }}</el-button>
      </el-form-item>
      <el-form-item prop="newPassword" v-if="stepActive === 2">
        <el-input autocomplete="off" v-model="resetPasswordForm.newPassword" type="password" show-password :placeholder="t('login.newPassword')" />
      </el-form-item>
      <el-form-item prop="newPasswordSure" v-if="stepActive === 2">
        <el-input autocomplete="off" v-model="resetPasswordForm.newPasswordSure" type="password" show-password :placeholder="t('login.confirmPassword')" />
      </el-form-item>
      <el-form-item v-if="stepActive === 3">
        <img :src="images.success" alt="" class="reset-password-success">
        <el-button type="primary" size="large" @click="toBack">{{t('motion.close')}}</el-button>
      </el-form-item>
      <el-form-item class="reset-pssword-btn" v-if="stepActive < 3">
        <el-button type="primary" size="large" @click="resetPassword" :loading="loading.resetPasswordLoading">{{t('login.next')}}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts" name="Forgetpassword">
import loginApi from '@/api/modules/login';
import userinfoApi from '@/api/modules/userinfo';
import system from '@/store/system';

const piniaSystem = system();
const langAreaList:any = computed(()=>piniaSystem.getLangList);
const { t } = useI18n();
const emits = defineEmits(['back']);

const props = defineProps({
  backTitle: {
    type: String,
    default: 'login'
  },
  isPhoneLogin: {
    type: Boolean,
    default: false
  }
});

const images = reactive({
  phone: new URL('../../assets/images/login/phone.svg', import.meta.url).href,
  google: new URL('../../assets/images/login/google.svg', import.meta.url).href,
  fb: new URL('../../assets/images/login/fb.svg', import.meta.url).href,
  email: new URL('../../assets/images/login/email.svg', import.meta.url).href,
  success: new URL('../../assets/images/login/success.svg', import.meta.url).href,
});

const data: any = reactive({
  steps: [
    {
      label: computed(()=> t('login.verify1'))
    },
    {
      label: computed(()=> t('login.set'))
    },
    {
      label: computed(()=> t('login.success'))
    },
  ],
  resetPasswordFormRef: null,
  resetPasswordForm: {
    area: piniaSystem.getLang.countryCode,
  },
  resetPasswordFormRules: {
    userName: [
      { required: true, message: computed(()=>props.isPhoneLogin ? t('login.text_010') : t('login.accountEnter')), trigger: 'blur' },
    ],
    password: [
      { required: true, message: computed(()=>t('login.psdRule')), trigger: 'blur' },
      { min: 8, max: 16, message: computed(()=>t('login.psdRule')), trigger: 'blur' },
    ],
    code: [
      { required: true, message: computed(()=>t('login.verifiyRule')), trigger: 'blur' },
    ],
    newPassword: [
      { required: true, message: computed(()=>t('login.psdRule')), trigger: 'blur' },
      { min: 8, max: 16, message: computed(()=>t('login.psdRule')), trigger: 'blur' },
    ],
    newPasswordSure: [
      { required: true, message: computed(()=>t('login.psdRule')), trigger: 'blur' },
      { validator: (rule: any, value: any, callback: any) => {
        if (value === '') {
          callback(new Error(t('login.enterAgain')))
        } else if (value !== resetPasswordForm.value.newPassword) {
          callback(t('login.diffrencePsd'))
        } else {
          callback()
        }
      }, trigger: 'blur' },
    ],
  },
  loading: {
    passwordLoading: false,
    resetPasswordLoading: false,
    signupLoading: false,
  },
  disabled: {
    passwordDisabled: true
  },
  sliderLoginStatus: false,
  sliderRef: null,
  getLoginCodeTxt: t('home.PhoneGetCode'),
  getLoginCodeDisabled: false,
  getResetPasswordCodeTxt: t('home.PhoneGetCode'),
  getResetPasswordCodeDisabled: false,
  getSignupCodeTxt: t('home.PhoneGetCode'),
  getSignupCodeDisabled: false,
  stepActive: 1,
  sliderSignupStatus: false,
  signupForm: {
    agreement: true
  },
  signupFormRef: null,
  signupFormRules: {
    email: [
      { required: true, message: computed(()=>t('login.accountEnter')), trigger: 'blur' },
    ],
    phone: [
      { required: true, message: computed(()=>t('login.text_010')), trigger: 'blur' },
    ],
    password: [
      { required: true, message: computed(()=>t('login.psdRule')), trigger: 'blur' },
      { min: 8, max: 16, message: computed(()=>t('login.psdRule')), trigger: 'blur' },
    ],
  }
});

const {
  steps,
  resetPasswordFormRef,
  resetPasswordForm,
  resetPasswordFormRules,
  loading,
  stepActive,
  getResetPasswordCodeTxt,
  getResetPasswordCodeDisabled,
} = toRefs(data);

// 重置密码
const resetPassword = () => {
  resetPasswordFormRef.value.validate((valid:any, fields:any) => {
    if (valid) {
      loading.value.resetPasswordLoading = true;
      if(stepActive.value === 1){
        emailSendAuth();
      }else if(stepActive.value === 2){
        // 充值密码
        resetPasswordQuery();
      }
    }else{
      // 重置 滑块 ?
    }
  });
}

// 充值密码
const resetPasswordQuery = () => {
  userinfoApi.resetPassword({
    newPassword: resetPasswordForm.value.newPassword,
    userName: resetPasswordForm.value.userName,
    type: 1
  }).then((response:any)=>{
    if(response.code === 200){
      // 成功后跳转
      stepActive.value ++;
    }
  }).finally(()=>{
    loading.value.resetPasswordLoading = false;
  });
}

// 验证 验证码是否正确
const emailSendAuth = () => {
  loginApi.emailSendAuth({
    code: resetPasswordForm.value.code,
    email: resetPasswordForm.value.userName
  }).then((response:any)=>{
    if(response.code === 200){
      // 成功后跳转
      stepActive.value ++;
    }
  }).finally(()=>{
    loading.value.resetPasswordLoading = false;
  });
}

// 重置密码code
const getCodeOfResetPassword = () => {
  getResetPasswordCodeDisabled.value = true;
  getCodeTimer(getResetPasswordCodeTxt, getResetPasswordCodeDisabled);
  getVerifiy(resetPasswordForm.value);
}

// 获取验证码
const getVerifiy = (whichForm: any) => {
  if(props.isPhoneLogin){
    // 手机验证码
    loginApi.getPhoneVerifiy({
      phone: `${whichForm.area}${whichForm.userName}`
    }).then((response:any)=>{
      console.log("手机验证码", response)
    });
  }else{
    // 邮箱验证码
    loginApi.getEmailVerifiy({
      email: whichForm.userName
    }).then((response:any)=>{
      console.log("邮箱验证码", response)
    });
  }

}

// 倒计时
const getCodeTimer = (txt: any, disable: any) => {
  let timer:any = null;
  let countdown:number = 59;
  if(timer){ return; }
  const callback = function(){
    if(countdown <= 0){
      txt.value = t('home.PhoneGetCode');
      disable.value = false;
      clearInterval(timer);
    }else{
      txt.value = countdown--;
    }
  }
  callback();
  timer = setInterval(callback, 1000);
}


// 返回登录
const toBack = () => {
  stepActive.value = 1;
  emits('back');
}
</script>

<style lang="scss" scoped>
@import url('./index.scss');
.z-dialog-wrapper-h5{
  .login-content{
    margin-top: var(--rem-200) !important;
    height: calc(100% - var(--rem-200)) !important;
    &.sign-up{
      padding-top: 0 !important;
    }
  }
}
</style>
